﻿/// <reference path="Meres.js" />

administration = function () {
    this.installPluggin = function () {
        installjQueryPlugin();
    };
    this.installPluggin();

    // Reg UI event
    function installjQueryPlugin() {
        var layout = $('#adminView').layout();
        layout.sizePane("west", 250);

        $("#functionalities").selectable({
            selected: function (ev, ui) {
                openFunc($(ui.selected).attr('id'));
            }
        });
    }

    function installjsTree() {
        $('#membershipGroupTree')
        .bind("before.jstree", function (e, data) {
            //Meres.log(data.func);
        })

        .jstree({
            "themes": {
                "theme": "default",
                "url": "/Modules/Eking.Framework/Styles/TreeView1.css",
                "icons": false
            },

            "json_data": {
                // This tree is ajax enabled - as this is most common, and maybe a bit more complex
                // All the options are almost the same as jQuery's AJAX (read the docs)
                "ajax": {
                    // the URL to fetch the data
                    "url": "/Meres/HtmlTree/GroupOperation",
                    // the `data` function is executed in the instance's scope
                    // the parameter is the node being loaded 
                    // (may be -1, 0, or undefined when loading the root nodes)
                    "data": function (n) {
                        // the result is fed to the AJAX request `data` option
                        return {
                            "operation": "GetGroupChildren",
                            "id": n.attr ? n.attr("id").replace("node_", "") : 1
                        };
                    }
                }
            },
            "plugins": ["themes", "json_data", "ui", "contextmenu", "crrm"]

        })
        .bind('select_node.jstree', function (event, data) {
            return;
        })
        .bind("rename.jstree", function (e, data) {

        });

        $('#renameTreeItem').click(function () {
            $('#membershipGroupTree').jstree('rename');
        });

    }

    var tableModels = undefined;
    function openFunc(funcid) {
        var url = "/Meres/Administration/AdminFunctionView?funcId=" + funcid;
        doAjax(url, function (evt) {
            var html = evt;
            if (funcid == 6) {
                html = evt.Html;
                tableModels = evt.ViewModel;
            }

            $('#adminView .functionContent').html(html);
            if (funcid == 1) {
                installjsTree();
            }

            if (funcid == 6) {
                $('#tableModels').change(function () {
                    //$('#tableData').html($(this).val());
                    installDbTableGridEditor($(this).val());
                });
            }

            if (funcid == 7) {
                installJsonEditor();
            }
        });
    }

    function installDbTableGridEditor(tableName) {
        if (tableName == "None") {
            $('#tableDataArea').html("-- Select a table -");
            return;
        }

        $('#tableDataArea').html('<table id="tableData"></table><div id="tableDataPager"></div>');
        var gw = $('#adminView .functionContent').width();
        var gh = $('#adminView .functionContent').height();


        var table = tableModels.singleOrDefault(function (item) {
            return item.Name == tableName;
        });

        var colNames = [];
        var colModels = [];
        var keys = table.Columns.where(function (item) {
            return item.IsPrimaryKey;
        });
        for (var i = 0; i < table.Columns.length; i++) {
            var colName = table.Columns[i].Name;
            colNames.push(colName);
            var colModel = { name: colName, index: colName, with: 30, align: "left", vertical: "middle", editable: true };
            if (table.Columns[i].IsPrimaryKey && keys.length <= 1)
                colModel.editable = false;
            colModels.push(colModel);
        }


        $("#tableData").jqGrid({
            url: '/Meres/Administration/TableDatajqGridQuery',
            postData: { tableModel: JSON.stringify(table) },
            datatype: "json",
            mtype: "POST",
            colNames: colNames,
            colModel: colModels,
            // Grid total width and height
            width: gw,
            height: gh - 94,

            // Paging                    
            pager: $("#tableDataPager"),
            rowNum: 20,
            rowList: [5, 10, 20, 50, 100, 1000],
            viewrecords: true,
            // Default sorting
            sortorder: "asc",

            // Grid caption
            caption: tableName,
            editurl: '/Meres/Administration/TableDatajqGridEdit?tableModel=' + JSON.stringify(table)

        }).navGrid("#tableDataPager",
                       {
                           refresh: true, add: true, edit: true, del: true
                       },
                       {}, // settings for edit
                       {}, // settings for add
                       {}, // settings for delete
                       { sopt: ["cn"] } // Search options. Some options can be set on column level
                    );

        $("#tableData").jqGrid('navGrid', "#tableData", { edit: false, add: false, del: false });
        $("#tableData").jqGrid('inlineNav', "#tableData");
    }

    var jsonEditorContext = undefined;
    function installJsonEditor() {
        var loadFunc = function (opts) {
            doAjax("/Meres/Administration/LoadJsonFile?fileName=" + opts.file,
                function (evt) {
                    var dat = eval(evt);
                    opts.success(dat);
                    jsonEditorContext = { file: opts.file, json: dat };
                });
        };

        JSONeditor.start('tree', 'jform', false, true, { loadFunc: loadFunc });
        Opera = (navigator.userAgent.toLowerCase().indexOf("opera") != -1);
        Safari = (navigator.userAgent.toLowerCase().indexOf("safari") != -1);
        Explorer = (document.all && (!(Opera || Safari)));
        Explorer7 = (Explorer && (navigator.userAgent.indexOf("MSIE 7.0") >= 0));

        if (Explorer7 && location.href.indexOf("file:") != 0) { prompt("This is just to get input boxes started in IE7 - who deems them unsecure.", "I like input boxes...") }

        $('#btnSaveJson').click(function () {
            var txt = JSON.stringify(JSONeditor.getJson());
            txt = jsonEditorContext.file.replaceAll(".js", "")
            .replaceAll(" ", "")
            .replaceAll(".", "")
            + "=" + txt;

            doAjax("/Meres/Administration/SaveJsonFile", undefined, { fileName: jsonEditorContext.file, content: txt }, 'POST');
        });
    }

}
